function hfile = dmr_SaveDWI(hfile, totio)
% DMR::SaveDWI  - save memory-bound DWI data
%
% FORMAT:       [dmr] = dmr.SaveDWI([totio]);
%
% Input fields:
%
%       totio       if given and true convert data to transio object
%
% No output fields.
%
% Note: if the DWIData field is a transio, the function does nothing.

% Version:  v0.7b
% Build:    7083114
% Date:     Aug-31 2007, 2:05 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'dmr')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
if nargin < 2 || ...
   ~islogical(totio) || ...
    isempty(totio)
    totio = false;
else
    totio = totio(1);
end

% try saving the DWI
sc = bvqxfile_getscont(hfile.L);
bc = sc.L;
if istransio(bc.DWIData)
    return;
end
[dfpn{1:3}] = fileparts(sc.F);
dsf = bc.DataStorageFormat;
nov = bc.NrOfVolumes;
nos = bc.NrOfSlices;
rsx = bc.ResolutionX;
rsy = bc.ResolutionY;
switch (dsf)
    case {2}
        dds = [rsx, rsy, nov, nos];
    case {3}
        dds = [rsx, rsy, nos, nov];
    case {4}
        dds = [nov, rsx, rsy, nos];
    otherwise
        error( ...
            'BVQXfile:InvalidObject', ...
            'Unsupported DataStorageFormat field.' ...
        );
end
if ~isequal(size(bc.DWIData), dds) || ...
   ~isa(bc.DWIData, 'uint16')
    error( ...
        'BVQXfile:InvalidObject', ...
        'Invalid DataStorageFormat, dimensions and/or datatype.' ...
    );
end

% create filename
if any(dfpn{3}(2:end) == upper(dfpn{3}(2:end)))
    dfpn{3} = '.DWI';
else
    dfpn{3} = '.dwi';
end
dwif = [dfpn{1} '/' dfpn{2} dfpn{3}];
try
    dwii = fopen(dwif, 'w', 'ieee-le');
    if dwii < 1
        error('FILEOPEN_FAILED');
    end
    fwrite(dwii, bc.DWIData(:), 'uint16');
    fclose(dwii);
catch
    error( ...
        'BQVXfile:FileNotWritable', ...
        'File not writable: ''%s''.', ...
        dwif ...
    );
end

% reload as transio?
if totio
    try
        bc.DWIData = transio(dwif, 'ieee-le', 'uint16', 0, dds);
    catch
        error( ...
            'BVQXfile:transioError', ...
            'Error reopening the written file as transio: %s.', ...
            lasterr ...
        );
    end
    bvqxfile_setcont(hfile.L, bc);
end
